<template>
  <div class="user-info">
    

    <eagle-sing-diy  ref="setzIndex" :isContinue="false" :mzIndex="this.zIndex" :id="id" v-on:FilePathClick="FilePathClick"></eagle-sing-diy>

    <div class="read-pdf">
      <pdf ref="pdf" v-for="i in numPages" :key="i" :src="url" :page="i"></pdf>
    </div>
    <van-button
      class="button-fixed"
      type="info"
      block
      @click="submit"
      v-if="isSignatureBool"
    >
      签字
    </van-button>
    <div class="bottom-btns m-10 btns">
        <eagle-button style="flex:1;" class="mls"  @click="handleClose(1)" v-if="signState < 1">检查人签名</eagle-button>
        <eagle-button style="flex:1;" class="mls" type="orange" @click="handleClose(2)" v-if="signState == 1 || signState == 2">被检查企业签名</eagle-button>
      </div>
  </div>
</template>

<script>
import pdf from "vue-pdf";
import EagleSingDiy from '../../../components/eagle-sing-diy.vue';
import {
  CommonAttachUploadBase64,
  SiteAppointmentSign,
  SitePromiseRecordSign,
  SiteSafeCostPlanMainSign,
  
} from "@/api/common";
import { mapGetters } from "vuex";
export default {
  components: {
    pdf,
    EagleSingDiy, 
  },
  data() {
    return {
      adds: "",
      zIndex: -8,
      isCertificate: true,
      isCertificate2: false,
      stageInfo: "",
      client: {},
      points: [],
      canvasTxt: null,
      startX: 0,
      startY: 0,
      moveY: 0,
      moveX: 0,
      endY: 0,
      endX: 0,
      w: null,
      h: null,
      isDown: false,
      isViewAutograph: this.$route.query.isViews > 0,
      contractSuccess: this.$route.query.contractSuccess,
      url: ``,
      urlOld: ``,
      numPages: 0, // pdf 总页数
      TypeName: null,
      isSignature: null,
      isSignatureBool: false,
      id: this.$route.query.id,
      signState: this.$route.query.signState,
      DocCode: this.$route.query.DocCode,
    };
  },
  created() {
    this.$toast.loading({
      message: "加载中...",
      forbidClick: true,
    });
  },

  computed: {
    ...mapGetters(["baseUrl", "CompanyCode", "roles"]),
  },

  mounted() {
    this.url = this.$route.query.url;
    this.urlOld = this.$route.query.url;
    this.signState = this.$route.query.signState;
    this.TypeName = this.$route.query.TypeName;
    this.isSignature = this.$route.query.isSignature;
    this.id = this.$route.query.id;
    this.DocCode = this.$route.query.DocCode;

    if (this.url) {
      if (this.signState == 1) {
        this.url = this.url.replace(".pdf","-temp.pdf");
      } else if (this.signState == 2 || this.signState == 3) {
        this.url = this.url.replace(".pdf","-sign.pdf");
      }
    }
    if (
      this.isSignature == "isSignature" ||
      this.isSignature == "forSignature" ||
      this.isSignature == "ProjectEntrustedOnlineDoc" ||
      this.isSignature == "SitePromiseRecordSign" ||
      this.isSignature == "SiteSafeCostPlanMain" ||
      this.isSignature == "ResponsibilityOrgPostUserDepositManage"
    ) {
      this.isSignatureBool = true;

      let canvas = this.$refs.canvasF;
      canvas.height = this.$refs.canvasHW.offsetHeight - 500;
      canvas.width = this.$refs.canvasHW.offsetWidth - 50;
      this.canvasTxt = canvas.getContext("2d");
      this.stageInfo = canvas.getBoundingClientRect();
    }
    this.getNumPages();
  },
  methods: {
    // # 计算pdf页码总数
    submit() {
      if (this.isSignature == "ProjectEntrustedOnlineDoc") {
        //任命书文件签名
        this.AddCertificate("ProjectEntrustedOnlineDoc");
      } else if (this.isSignature == "SitePromiseRecordSign") {
        //承诺书文件签名
        this.AddCertificate("SitePromiseRecordSign");
      } else if (this.isSignature == "SiteSafeCostPlanMain") {
        //安全经费投入计划
        this.AddCertificate("SiteSafeCostPlanMain");
      } else if (this.isSignature == "ResponsibilityOrgPostUserDepositManage") {
        this.$router.push({
          path: "/ProductionSafetySign",
          query: { DutyCode: this.DocCode },
        });
      } else {
        this.$router.push({
          path: "/GuidelineEntrustedRegPostDuty",
          query: {
            IDS: this.id,
            TypeName: this.$route.query.TypeName,
            isSignature: this.isSignature,
          },
        });
      }
    },
    getNumPages() {
      let loadingTask = pdf.createLoadingTask(this.url);
      loadingTask.promise
        .then((pdf) => {
          this.numPages = pdf.numPages;
        })
        .catch((err) => {
          console.error("pdf 加载失败", err);
        });
    },

    //控制弹窗是否显示
    AddCertificate(add) {
      this.adds = add;
      this.zIndex = 8;
      this.isCertificate = true;
      this.isCertificate2 = true;
      this.overwrite();
    },
    Canvas_goBack() {
      this.zIndex = -8;
      this.isCertificate = false;
      this.isCertificate2 = false;
    },
    //重写
    overwrite() {
      this.canvasTxt.clearRect(
        0,
        0,
        this.$refs.canvasF.width,
        this.$refs.canvasF.height
      );
      this.points = [];
    },
    // 上传图片
    afterRead(base64) {
      var params = {
        Img: base64,
      };
      CommonAttachUploadBase64(params)
        .then((res) => {
          this.Sign(res.data.FilePath);
        })
        .catch((err) => {
          console.log("err", err);
        });
    },
    //提交签名
    commit() {
      this.afterRead(this.$refs.canvasF.toDataURL());
    },

    Sign(url) {
      if (this.isSignature == "SitePromiseRecordSign") {
        var data = {
          SignPic: url,
          CompanyCode: this.CompanyCode,
          DocCode: this.DocCode,
          Code: this.DocCode,
        };

        SitePromiseRecordSign(data)
          .then((res) => {
            setTimeout(() => {
              this.$router.goRefresh(-1);
            }, 500);
          })
          .catch((err) => {
            console.log("err", err);
          });
      } else if (this.isSignature == "ProjectEntrustedOnlineDoc") {
        var data = {
          SignPic: url,
          CompanyCode: this.CompanyCode,
          DocCode: this.DocCode,
        };
        SiteAppointmentSign(data)
          .then((res) => {
          setTimeout(() => {
            this.$router.goRefresh(-1);
          }, 500);
          })
          .catch((err) => {
            console.log("err", err);
          });
      } else if (this.isSignature == "SiteSafeCostPlanMain") {
        var data = {
          SignPic: url,
          CompanyCode: this.CompanyCode,
          DocCode: this.DocCode,
          Code: this.DocCode,
        };

        SiteSafeCostPlanMainSign(data)
          .then((res) => {
          setTimeout(() => {
            this.$router.goRefresh(-1);
          }, 500);
          })
          .catch((err) => {
            console.log("err", err);
          });
      }
    },

    // 签字
    FilePathClick(FilePath) {
      
      this.imgUrl = FilePath;
      
       console.log("http==========>"+FilePath);
      this.autoGraph()
    },

    // 结束按钮
    autoGraph() {
      let that = this;
      let params = {
        ID: that.id,
        SignAttach : that.imgUrl
      }
      if (this.adds == 1) {
          that.$axios
          .post("/OtherDangerReport/CheckerSign",params)
          .then((res)=>{
            that.$toast.success("签名成功！");
            setTimeout(() => {
              that.signState = res.data;

              if (that.signState == 1) {
                that.url = that.urlOld.replace(".pdf","-temp.pdf");
              } else if (that.signState == 2 || that.signState == 3) {
                that.url = that.urlOld.replace(".pdf","-sign.pdf");
              }
              
              that.getNumPages();
                
            }, 500);
          })
          .catch(() => {
            // on cancel
          });
        } else if (this.adds == 2) {
          that.$axios
          .post("/OtherDangerReport/Sign",params)
          .then((res)=>{
            that.$toast.success("签名成功！");


            setTimeout(() => {
               that.signState = res.data;

               if (that.signState == 1) {
                  that.url = that.urlOld.replace(".pdf","-temp.pdf");
                } else if (that.signState == 2 || that.signState == 3) {
                  that.url = that.urlOld.replace(".pdf","-sign.pdf");
                }
               that.getNumPages();
            }, 500);

           
          })
          .catch(() => {
            // on cancel
          });
        }
    },

    // 签名
    handleClose(add){
      this.adds = add;
      this.zIndex = 8;
      this.isCertificate = true;
      this.isCertificate2 = true;
      this.$refs.setzIndex.setzIndex(this.zIndex);
      // this.overwrite();
    },

    // SiteAppointmentSign(data).then.((res)
    //         =>{

    //         });
  },
};
</script>

<style lang="less" scoped>

.bottom-btns {
  padding: 0 10px;
  position: fixed;
  bottom: 0px;
  align-items: center;
  justify-content: space-between;
  display: flex;
  align-items: center;
  width: 100%;;
  .submit-btn {
    width: 32%;
    height: 35px;
    font-size: 14px;
  }
  .delete-btn {
    width: 100%;
    height: 35px;
    font-size: 14px;
  }
}

.read-pdf {
  min-height: 100vh;
}

.button-fixed {
  position: fixed;
  bottom: 0px;
}
.popup2 {
  width: 100%;
  height: 100%;
  padding-top: 16px;
  padding-bottom: 16px;
  text-align: center;
  border-radius: 7px;
}
.user-info {
  min-height: 100vh;
  background-color: #fff;
}
.imgCanvas {
  /* background-color: #71b900; */
  border: 1px solid #7d7d7d;
  width: 50px;
  height: 50px;
}
.signatureBox-popup {
  opacity: 1;
  background: #666;
  display: none;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  display: flex;
  padding-top: 200px;
}

.signatureBox {
  width: 100%;
  height: calc(100% - 50px);
  box-sizing: border-box;
  overflow: hidden;
  background: #fff;
  height: 60%;
  z-index: 8;
  display: inline-flex;
  flex-direction: column;
}
.canvasBox {
  box-sizing: border-box;
  flex: 1;
  height: 100%;
}
canvas {
  margin: 20px;
  width: 90%;
  /* height: 200px; */
  border: 1px solid #7d7d7d;
}
.btnBox {
  padding: 10px;
  text-align: center;
}
.btnBox button:first-of-type {
  background: transparent;
  border-radius: 4px;
  height: 40px;
  width: 80px;
  font-size: 14px;
}
.btnBox button:last-of-type {
  background: #71b900;
  color: #fff;
  border-radius: 4px;
  height: 40px;
  width: 80px;
  font-size: 14px;
}
.mls{
    margin-right: 5px;
  }
</style>